// pages/order/person_list.js
const app = getApp();

let req = require('../../utils/request.js');
let api = require('../../utils/api.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    toggle: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showLoading({
      title: '加载中',
    })
    var _this = this,
        user_token = app.globalData.userInfo.user_token
    
    req.request(
      api.getUserAllPassenger,
      {method: 'POST', data: {user_token: user_token}},
      function(res) {
        wx.hideLoading()
        res = res.data

        var storage = wx.getStorageSync('persons'),
            toggle = _this.data.toggle
        
        for(var i in res) {
          for(var j in storage) {
            if(storage[j].person_id == res[i].person_id) {
              toggle[i] = 'checked'
            }
          }
        }

        _this.setData({user_person: res, toggle: toggle})
      }
    )
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  //将用户添加到待乘列表
  addToOrder(e) {
    var id = e.currentTarget.id,
        index = e.currentTarget.dataset.index,
        toggle = e.currentTarget.dataset.toggle,
        _this = this,
        user_person = _this.data.user_person,
        data = {}

    if(toggle == '') {
      data['toggle[' + index + ']'] = 'checked'
    }else {
      data['toggle[' + index + ']'] = ''
    }

    _this.setData(data)
  },
  check() {
    var _this = this,
        user_person = _this.data.user_person,
        toggle = _this.data.toggle,
        data = []

    for(var i in toggle) {
      if (toggle[i] == 'checked') {
        data.push(user_person[i])
      }
    }

    wx.setStorage({
      key: 'persons',
      data: data,
    })

    wx.navigateBack({
      delta: 1
    })
  }
})